package com.weakteam.androidclient.data;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Nail
 */
public class DataRequest extends AsyncTask<Void, Void, Void> {

    private Map<String, String> dataMap;
    private Activity activity;
    private URL url;
    private int timeout;
    private String outData;
    private File file;

    private ITextResponse textResponse;
    private IFileResponse fileResponse;

    public DataRequest(Activity activity) {
        this.activity = activity;
        this.timeout = 10000;
    }

    public void addTextResponse(ITextResponse response) {
        this.textResponse = response;
    }

    public void addFileResponse(IFileResponse response, File file) {
        this.fileResponse = response;
        this.file = file;
    }

    public void setTimeout(int timeoutMillis) {
        this.timeout = timeoutMillis;
    }

    public void setURL(String url) {
        try {
            this.url = new URL(url);
        } catch (MalformedURLException ex) {
            Log.e("android-client", "setURL io url: " + ex.toString());
        }
    }

    public void addData(String key, String value) {
        if (this.dataMap == null) {
            this.dataMap = new HashMap<String, String>();
        }
        this.dataMap.put(key, value);
    }


    public boolean send() {
        if (this.isNetworkAvailable()) {
            this.execute();
            return true;
        } else {
            return false;
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager)this.activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            HttpURLConnection connect = (HttpURLConnection) this.url.openConnection();

            if (this.dataMap == null) {
                connect.setRequestMethod("GET");
            } else {
                connect.setRequestMethod("POST");
                connect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connect.setRequestProperty("Content-length", "0");
            }

            this.outData = null;

            connect.setUseCaches(false);
            connect.setAllowUserInteraction(false);
            connect.setConnectTimeout(timeout);
            connect.setReadTimeout(timeout);
            connect.connect();
            int status = connect.getResponseCode();

            switch (status) {
                case 200:
                case 201:
                    if (textResponse != null) {
                        final BufferedReader br = new BufferedReader(new InputStreamReader(this.url.openStream(), "UTF-8"));
                        final StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = br.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        br.close();
                        this.outData = sb.toString();
                    }
                    if (fileResponse != null) {
                        Log.i("android-client", "start create file");
                        Log.i("android-client", this.file.getAbsolutePath());
                        final InputStream inputStream = this.url.openStream();
                        final FileOutputStream outputStream = new FileOutputStream(this.file);
                        byte[] buffer = new byte[4 * 1024];
                        int readSize;
                        while ((readSize = inputStream.read(buffer)) != -1) outputStream.write(buffer, 0, readSize);
                        outputStream.flush();
                        outputStream.close();
                    }
            }
        } catch (MalformedURLException ex) {
            Log.e("android-client", "doInBackground io url: " + ex.toString());
        } catch (IOException ex) {
            Log.e("android-client", "doInBackground io ex: " + ex.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (textResponse != null) {
            this.textResponse.onTextResponse(this.outData);
        }
        if (fileResponse != null) {
            this.fileResponse.onFileResponse(this.file);
        }
    }

}
